import 'dart:async';
import 'dart:collection';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_single_choice_button_widget/common_single_choice_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_title_edit_with_underline_widget/typeof/common_title_edit_with_underline_typeof.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/department_or_class_list_response.dart';
import 'package:e_reception_flutter/ui/company/company_detail/class_or_department/class_or_department_page.dart';
import 'package:e_reception_flutter/ui/company/company_detail/class_or_department/class_or_department_viewmodel.dart';
import 'package:e_reception_flutter/ui/company/company_detail/widgets/stitching_avatar_widget.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/rich_text_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

class SelectClassOrDepartmentPage extends StatefulWidget {
  final int type;

  final List<String> selectIds;

  const SelectClassOrDepartmentPage({Key key, this.type, this.selectIds})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return SelectClassOrDepartmentState();
  }

  ///跳转方法
  static Future<EditTextAndValue> navigatorPush(
      BuildContext context, int type, selectIds) {
    return RouterUtils.routeForFutureResult<EditTextAndValue>(
      context,
      SelectClassOrDepartmentPage(
        type: type,
        selectIds: selectIds,
      ),
      routeName: ClassOrDepartmentPage.ROUTER,
    );
  }
}

class SelectClassOrDepartmentState
    extends BasePagerState<DepartmentOrClassListItemBean, SelectClassOrDepartmentPage> {
  ClassOrDepartmentViewModel _viewModel;
  List<DepartmentOrClassListItemBean> _selectBeans = List();
  List<String> _selectIds = List();

  bool allSelect;

  @override
  void initState() {
    _viewModel = ClassOrDepartmentViewModel(this);
    if (widget.selectIds != null) {
      _selectIds.addAll(widget.selectIds);
    }
    super.initState();
    _viewModel.refresh();
  }

  @override
  Widget build(BuildContext context) {
    return CustomAnnotatedRegion(
      Scaffold(
        backgroundColor:
            ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        body: Column(
          children: <Widget>[
            VgTopBarWidget(
              title: '请选择',
            ),
            Expanded(
              child: VgPlaceHolderStatusWidget(
                loadingStatus: data == null,
                emptyStatus: data?.isEmpty ?? false,
                child: VgPullRefreshWidget.bind(
                  state: this,
                  viewModel: _viewModel,
                  child: ScrollConfiguration(
                    behavior: MyBehavior(),
                    child: ListView.builder(
                      padding: EdgeInsets.zero,
                      itemBuilder: (context, index) {
                        return _listItem(index);
                      },
                      itemCount: data == null ? 0 : data.length,
                    ),
                  ),
                ),
              ),
            ),
            _toHorizontalBar()
          ],
        ),
      ),
      navigationBarColor:
          ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
    );
  }

  _listItem(int index) {
    DepartmentOrClassListItemBean item = data[index];

    // List<String> urlList = item?.picurls?.split(',') ?? [];
    // urlList.removeWhere((element) => StringUtils.isEmpty(element));
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () async {
        // SelectClassOrDepartmentBean bean=  SelectClassOrDepartmentBean(item.name,item.id,item.memberCnt);
        if (_selectIds.contains(item.getId())) {
          _selectIds.remove(item.getId());
        } else {
          _selectIds.add(item.getId());
        }

        if(data.length == _selectIds?.length){
          allSelect = true;
        }else{
          allSelect = false;
        }
        setState(() {});
      },
      child: Container(
        height: 60,
        color: ThemeRepository.getInstance().getCardBgColor_21263C(),
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 15, vertical: 11),
          child: Row(
            children: [
              Padding(
                padding: const EdgeInsets.only(right: 10),
                child: CommonSingleChoiceButtonWidget(
                    (_selectIds.contains(item.getId()))
                        ? CommonSingleChoiceStatus.selected
                        : CommonSingleChoiceStatus.unSelect),
              ),
              ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: Container(
                  height: 36,
                  width: 36,
                  child: VgCacheNetWorkImage(
                    item?.dpPicurl??"",
                    fit: BoxFit.cover,
                    imageQualityType: ImageQualityType.middleDown,
                    defaultErrorType: ImageErrorType.head,
                    defaultPlaceType: ImagePlaceType.head,
                    emptyWidget: Container(
                      width: 36,
                      height: 36,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        border: Border.all(color: Color(0xffd0e0f7), width: 1),
                      ),
                      child: Image.asset(
                        "images/icon_default_depart_logo.png",
                        width: 36,
                        height: 36,
                      ),
                    ),
                  ),
                ),
              ),
              // StitchingAvatarWidget(
              //   avatarUrlList: urlList,
              //   emptyWidget: Container(
              //     width: 36,
              //     height: 36,
              //     decoration: BoxDecoration(
              //       borderRadius: BorderRadius.all(Radius.circular(4)),
              //       border: Border.all(color: Color(0xffd0e0f7), width: 1),
              //     ),
              //     child: Image.asset(
              //       "images/icon_default_depart_logo.png",
              //       width: 36,
              //       height: 36,
              //     ),
              //   ),
              // ),
              SizedBox(
                width: 10,
              ),
              Expanded(
                child: Stack(
                  children: <Widget>[
                    Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                            //名称
                            Container(
                              width: (VgToolUtils.getScreenWidth() /3)*2,
                              child: Text(
                                '${item?.getName() ?? '暂无'}',
                                style: TextStyle(
                                    fontSize: 15, color: Color(0xffd0e0f7)),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                          ],
                        ),
                        Spacer(),
                        Container(
                          //左侧显示成员数和刷脸数
                          child: Container(
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: <Widget>[
                                RichTextWidget(
                                  fontSize: 12,
                                  contentMap: LinkedHashMap.from({
                                    '${widget.type == ClassOrDepartmentPage.TYPE_DEPARTMENT ? '成员' : '学员'}':
                                        Color(0xff5e687c),
                                    '${item.memberCnt}':
                                        (item?.memberCnt ?? 0) > 0
                                            ? ThemeRepository.getInstance()
                                                .getPrimaryColor_1890FF()
                                            : Color(0xff5e687c),
                                    '人': Color(0xff5e687c)
                                  }),
                                ),
                                // Visibility(
                                //   visible: (item.faceCnt ?? 0) > 0,
                                //   child: RichTextWidget(
                                //     fontSize: 12,
                                //     contentMap: LinkedHashMap.from({
                                //       '，今日刷脸': Color(0xff5e687c),
                                //       '${item.faceCnt ?? 0}':
                                //       ThemeRepository.getInstance()
                                //           .getPrimaryColor_1890FF(),
                                //       '人': Color(0xff5e687c),
                                //     }),
                                //   ),
                                // ),
                              ],
                            ),
                          ),
                        )
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _toHorizontalBar() {
    int count = _selectIds?.length ?? 0;
    return Container(
      height: 56,
      color: Color(0xFF3A3F50),
      // margin: const EdgeInsets.symmetric(horizontal: 15),
      child: Row(
        mainAxisSize: MainAxisSize.max,
        children: <Widget>[
          SizedBox(
            width: 15,
          ),
          GestureDetector(
              onTap: () {
                allSelect = !(allSelect??false);
                if(allSelect){
                  _selectIds.clear();
                  data.forEach((element) {
                    _selectIds.add(element.getId());
                  });
                }else{
                  _selectIds.clear();
                }

                setState(() {});
              },
              child: Text("${allSelect??false?"全不选":"全选"}",
                  style: TextStyle(color: Color(0xFFD0E0F7), fontSize: 15))),
          SizedBox(
            width: 15,
          ),
          if (count > 0)
            Text("已选${count}${widget.type == ClassOrDepartmentPage.TYPE_DEPARTMENT ?"部门" :"班级"}",
                style: TextStyle(color: Color(0xFF1890FF), fontSize: 12)),
          Spacer(),
          _buttonWidget(),
          SizedBox(
            width: 15,
          ),
        ],
      ),
    );
  }

  Widget _buttonWidget() {
    return Container(
      child: CommonFixedHeightConfirmButtonWidget(
        isAlive: true,
        width: 90,
        height: 36,
        unSelectBgColor:
            ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
        selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
        unSelectTextStyle: TextStyle(
            color: VgColors.INPUT_BG_COLOR,
            fontSize: 15,
            fontWeight: FontWeight.w600),
        selectedTextStyle: TextStyle(
            color: Colors.white, fontSize: 15, fontWeight: FontWeight.w600),
        text: "确定",
        onTap: () {
          //提交按钮
          // if (isLightUp) {
          popResult();
          // }
        },
      ),
    );
  }

  ///返回选择结果
  void popResult() {
    StringBuffer showText = StringBuffer();
    if (_selectIds.length > 0) {
      data.forEach((element) {
        if (_selectIds.contains(element.getId())) {
          _selectBeans.add(element);
        }
      });
      if (_selectBeans?.length != 0 && _selectBeans != null) {
        showText.write('${_selectBeans.length}个');

        int totalCount = 0;
        if (widget.type == ClassOrDepartmentPage.TYPE_DEPARTMENT) {
          showText.write('部门');
        } else {
          showText.write('班级');
        }
        _selectBeans?.forEach((element) {
          totalCount += (element.memberCnt ?? 0);
        });
        showText.write('，共$totalCount人');
      }
    }
    RouterUtils.pop(context,
        result: EditTextAndValue(
            value: _selectBeans, editText: showText.toString()));
  }
}

class SelectClassOrDepartmentBean {
  String name;
  String id;
  int cnt;

  SelectClassOrDepartmentBean(this.name, this.id, this.cnt);
}
